package it.danghongphat.business;


import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import it.danghongphat.database.DatabaseManager;
import it.danghongphat.object.Dauky;

import javax.swing.table.AbstractTableModel;

public class DaukyBusiness {
	AbstractTableModel model;
	String headers[];
	DatabaseManager databaseManager=new DatabaseManager();
	public DaukyBusiness(AbstractTableModel model) {
		this.model=model;
	}
	public boolean insert(Dauky dk){
		String query = "INSERT INTO tondau VALUES ( '"
				+ dk.getMah() + "', '"
				+ dk.getMak() + "', '"
				+ dk.getSl() + "', '"
				+ dk.getDg() + "', '"
				+ dk.getTg() + "')"
				;
		if(databaseManager.excuteQuery(query)){
			databaseManager.closeConnection();
			return true;
		}
		else
			return false;
	}
	public boolean update(Dauky dk){
		String query = "UPDATE tondau SET mah = '"
				+ dk.getMah() + "', mak = '"
				+ dk.getMak() + "', sl = '" 
				+ dk.getSl()  + "', dg = '"
				+ dk.getDg()  + "', tg = '"
				+ dk.getTg()  + "' "
				+ " WHERE mah = '" + dk.getMah() + "'"	;
		if(databaseManager.excuteQuery(query)){
			databaseManager.closeConnection();
			return true;
		}
		else
			return false;
	}
	public boolean delete(Dauky dk){
		String query = "delete from tondau where mah = '" + dk.getMah() + "'"	;
		if(databaseManager.excuteQuery(query)){
			databaseManager.closeConnection();
			return true;
		}
		else
			return false;
	}
	public List<Dauky> LoadListDaukyList(){
		List<Dauky> list= new ArrayList<>();
		try{
			ResultSet rs = databaseManager.getResultSet("SELECT * FROM tondau");
			ResultSetMetaData meta = rs.getMetaData();
		    headers = new String[meta.getColumnCount()];
			for (int h = 1; h <= meta.getColumnCount(); h++) {
				  headers[h - 1] = meta.getColumnName(h);
			}
			
			while (rs.next()) {
		        Dauky dauky = new Dauky();
		        dauky.setMah(rs.getString(1));
		        dauky.setMak(rs.getString(2));
		        dauky.setSl(rs.getInt(3));
		        dauky.setDg(rs.getInt(4));
		        dauky.setTg(rs.getInt(5));
		        list.add(dauky);
		       }
				model.fireTableDataChanged();
		        databaseManager.closeConnection();
		 } catch (SQLException e) {
				e.printStackTrace();
		}
		return list;
	}
	public String[] getHeader(){
		return headers;
	}
}
